<?php
// User auth function

class Auth
{
	//Simple authentication.
	static function Simple($user,$pass)
	{
		$Sql = new SQL();
		//Prepare input.
		$User = $Sql->Sanitize($user);
		$Pass = $Sql->Sanitize($pass);
		//Check
		$res = $Sql->Query("SELECT * FROM ".TABLEPREF."users WHERE username='$User' AND user_password='$Pass'",1);
		if(!$res || $res==NULL)
		{
			//No matches from database, login failed.
			return false;
		}
		return true;
	}
	
	//Ensures the user still has a valid authentication.
	static function Check()
	{
		$Sql = new SQL();
		$res = $Sql->Query("SELECT * FROM ".TABLEPREF."users WHERE user_id='{$_SESSION['auth']['id']}' AND username='{$_SESSION['auth']['username']}' AND user_password='{$_SESSION['auth']['password']}'",1);
		if(!res || $res == NULL || $_SESSION['auth']['ip'] != $_SERVER['REMOTE_ADDR']) { return $_SESSION['auth']['authenticated'] = false; }
		return $_SESSION['auth']['authenticated'] = true;
	}
	
	//Authenticates a user using their session information.
	static function Session()
	{
		$Sql = new SQL();
		$res = $Sql->Query("SELECT * FROM ".TABLEPREF."users WHERE username='{$_SESSION['auth']['username']}' AND user_password='{$_SESSION['auth']['password']}'",1);
		if(!res || $res == NULL) { return false; }
		$_SESSION['auth']['id'] = (int)$res['user_id'];
		$_SESSION['auth']['ip'] = $_SERVER['REMOTE_ADDR'];
		return $_SESSION['auth']['authenticated'] = true;
	}
}
